# fake_source_meter.py
import time
import random
from utils.log_manager import logger
from PySide6.QtCore import QObject, QCoreApplication

class SourceMeterController(QObject):
    def __init__(self, address: str = None):
        super().__init__()
        self.address = address or "FAKE::2636B::INSTR"
        self.connected = False
        self.smua = None
        self.smub = None

        self.set_voltage = 0.0
        self.limit_current = 0.01
        self.sample_count = 3
        self.sample_interval_ms = 500

    def connect(self):
        """模拟连接设备"""
        time.sleep(0.5)
        self.connected = True
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 [模拟源表] 已连接: {address}").format(address=self.address))

    def disconnect(self):
        self.connected = False
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 [模拟源表] 已断开连接"))

    def is_connected(self):
        return self.connected

    def set_mode_voltage(self, channel='a'):
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 [{num}] 模拟设置为电压源模式").format(num=channel.upper()))

    def set_mode_current(self, channel='a'):
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 [{num}] 模拟设置为电流源模式").format(num=channel.upper()))

    def set_output_value(self, value: float, channel='a'):
        self.set_voltage = value
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 [{num}] 模拟设置输出值为 {value}V").format(num=channel.upper(),value=value))

    def set_protect_voltage(self, max_voltage: float, channel='a'):
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 [{num}] 模拟设置电压限制 {max_voltage}V").format(num=channel.upper(),max_voltage=max_voltage))

    def set_protect_current(self, max_current: float, channel='a'):
        self.limit_current = max_current
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 [{num}] 模拟设置电流限制 {max_current}A").format(num=channel.upper(),max_current=max_current))

    def output_on(self, channel='a'):
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 [{num}] 模拟输出已开启").format(num=channel.upper()))

    def output_off(self, channel='a'):
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 [{num}] 模拟输出已关闭").format(num=channel.upper()))

    def read_voltage(self, channel='a') -> float:
        """返回模拟电压，基于设定值微抖动"""
        value = round(self.set_voltage + random.uniform(-0.002, 0.002), 5)
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 [{num}] 模拟电压读数: {value}V").format(num=channel.upper(),value=value))
        return value

    def read_current(self, channel='a') -> float:
        """返回模拟电流"""
        value = round(random.uniform(0, self.limit_current), 6)
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 [{num}] 模拟电流读数: {value}A").format(num=channel.upper(),value=value))
        return value

    def read_power(self, channel='a') -> float:
        return self.read_voltage(channel) * self.read_current(channel)

    def _get_channel(self, channel):
        return self

    def apply_settings(self, voltage: float, limit_current: float, samples: int, interval_ms: int):
        self.set_voltage = voltage
        self.limit_current = limit_current
        self.sample_count = samples
        self.sample_interval_ms = interval_ms
        logger.log(QCoreApplication.translate("FakeSourceController","🧪 应用设置 电压={voltage}V 电流限制={limit_current}A 采样={samples} 间隔={interval_ms}ms").format(voltage=voltage, limit_current=limit_current, samples=samples, interval_ms=interval_ms))

    def perform_sampling(self, channel='a') -> dict:
        # 根据 UI 设置的次数和间隔采样
        # 返回：
        # {
        #     'voltages': [...],
        #     'currents': [...],
        #     'powers': [...],
        #     'voltage': ...,
        #     'current': ...,
        #     'power': ...
        # }
        voltages = []
        currents = []
        powers = []

        for i in range(self.sample_count):
            time.sleep(self.sample_interval_ms / 1000)

            v = self.read_voltage(channel)
            i_ = self.read_current(channel)
            p = v * i_

            voltages.append(v)
            currents.append(i_)
            powers.append(p)

            logger.log(QCoreApplication.translate("FakeSourceController","📊 采样 {i}/{sample_count}: V={v:.5f} V, I={i_:.5e} A, P={p:.6f} W").format(i=i+1, sample_count=self.sample_count, v=v, i_=i_, p=p))

        def median(lst):
            if not lst:
                return None
            index = len(lst) // 2
            return sorted(lst)[index]

        result = {
            "voltages": voltages,
            "currents": currents,
            "powers": powers,
            "voltage": median(voltages),
            "current": median(currents),
            "power": median(powers),
        }

        logger.log(QCoreApplication.translate("FakeSourceController","📈 中值：V={voltage:.5f} V, I={current:.5e} A, P={power:.6f} W").format(voltage=result['voltage'],current=result['current'],power=result['power']))

        return result
